package view;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;

import model.Vote;

public class LiveFeedPanel extends JPanel implements ActionListener {

	private ClientFrame frame;
	private JLabel userNameLabel;
	private JButton backButton;
	private JTextArea votedListTextArea;
	private JScrollPane scrollingArea;
	private Timer timer;
	private List<Vote> votedList;

	public LiveFeedPanel(ClientFrame f) {
		frame = f;
		this.setBounds(0, 0, frame.getWidth(), frame.getHeight());
		this.setBackground(Color.WHITE);
		this.setLayout(null);

		userNameLabel = new JLabel("Users voted: ");
		userNameLabel.setBounds(300, 150, 100, 20);
		this.add(userNameLabel);

		votedListTextArea = new JTextArea();
		updateFeed();
		votedListTextArea.setEditable(false);
		votedListTextArea.setWrapStyleWord(true);
		scrollingArea = new JScrollPane(votedListTextArea);
		scrollingArea.setBounds(300, 180, 200, 200);
		this.add(scrollingArea);

		backButton = new JButton("Back");
		backButton.setBounds(300, 390, 90, 20);
		backButton.addActionListener(this);
		this.add(backButton);

		this.repaint();

		frame.setContentPane(this);

		timer = new Timer(3000, this);
		timer.start();

	}

	@SuppressWarnings("unchecked")
	public void updateFeed() {
		try {
			Socket connectionSocket = new Socket("127.0.0.1", 4444);
			ObjectOutputStream objectOut = new ObjectOutputStream(
					connectionSocket.getOutputStream());
			ObjectInputStream objectIn = new ObjectInputStream(connectionSocket
					.getInputStream());

			objectOut.writeObject("get live feed voters list");
			objectOut.flush();
			votedList = (List<Vote>) objectIn.readObject();

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		String voted = "";
		int x = 1;
		for (Vote vote : votedList) {
			voted += x + ") " + vote.getVoterName() + ": "
					+ vote.getEncryptedVote() + "\n";
			x++;
		}

		votedListTextArea.setText(voted);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == backButton) {

			frame.goToLoginPanel();
		}

		if (e.getSource() == timer) {
			updateFeed();
		}

	}
}
